@echo off
:: Define MySQL bin path
set "mysqlPath=C:\Program Files\MySQL\MySQL Server 8.0\bin"

:: Check if path exists
if not exist "%mysqlPath%" (
    echo Error: Path does not exist. Check MySQL installation.
    pause
    exit /b 1
)

:: Check if already in system PATH
reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path 2>nul | findstr /i /c:"%mysqlPath%" >nul
if not errorlevel 1 (
    echo Path already exists in system PATH. No action needed.
    pause
    exit /b 0
)

:: Add to system PATH (requires admin)
for /f "tokens=2*" %%a in ('reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path 2^>nul') do (
    set "currentPath=%%b"
)
set "newPath=%currentPath%;%mysqlPath%"
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path /t REG_EXPAND_SZ /d "%newPath%" /f >nul 2>&1

:: Check result
if %errorlevel% equ 0 (
    echo Successfully added to system PATH.
) else (
    echo Failed to add. Run as Administrator.
    pause
    exit /b 1
)

echo Close all command windows and reopen to take effect.

:: 刷新环境变量，使其立即生效（无需重启）
setx Path "%Path%;%mysqlPath%" >nul 2>&1
echo 正在刷新环境变量...
refreshenv >nul 2>&1

echo 操作完成。请打开新的命令行窗口，输入 "mysql --version" 验证是否生效。
echo 开始执行数据库start...

pause
